package handler

import (
	"gitee.com/crack007/goose/gscore/server"
	"gitee.com/crack007/proxy/src/proxy/protocol"
	"gitee.com/crack007/proxy/src/proxy/service"
)

func NewTcpSessionHandler() *SessionHandler {
	return &SessionHandler{factoryProtocol: func(d *SessionHandler, session *server.Session) protocol.IProtocol {
		return protocol.NewTcp(session, d.Output)
	}}
}

func NewMysqlSessionHandler() *SessionHandler {
	return &SessionHandler{factoryProtocol: func(d *SessionHandler, session *server.Session) protocol.IProtocol {
		return protocol.NewMysql(session)
	}}
}

func NewRedisSessionHandler() *SessionHandler {
	return &SessionHandler{factoryProtocol: func(d *SessionHandler, session *server.Session) protocol.IProtocol {
		return protocol.NewRedis(session)
	}}
}

type SessionHandler struct {
	server.DefaultSessionHandle
	factoryProtocol func(d *SessionHandler, session *server.Session) protocol.IProtocol
	Host            string
	Port            uint16
	Output          string
}

func (d *SessionHandler) OnHandshake(session *server.Session) bool {
	return true
}

func (d *SessionHandler) OnConnect(session *server.Session) {
	proxySession := service.CreateProxySession(session)
	proxySession.SessionOpen(d.factoryProtocol(d, session), d.Host, d.Port)
}

func (d *SessionHandler) OnMessage(session *server.Session, data []byte) {
	service.GetProxySession(session).SendMsg(data)
}

func (d *SessionHandler) OnClose(session *server.Session, err error) {
	service.GetProxySession(session).Close()
	service.RemoveProxySession(session)
}
